﻿using Castle.ActiveRecord;

namespace Financial.Infra.DDD.AR
{
    public class ARGenericRepository<T> : IRepository<T>
        where T : class, IIdentifiable
    {
        public T Create(T entity)
        {
            ActiveRecordMediator<T>.Create(entity);

            return entity;
        }

        public T Update(T entity)
        {
            ActiveRecordMediator<T>.Update(entity);

            return entity;
        }

        public T CreateOrUpdate(T entity)
        {
            if (entity.Id == 0)
            {
                Create(entity);
            }
            else
            {
                Update(entity);
            }

            return entity;
        }

        public void Remove(T entity)
        {
            ActiveRecordMediator<T>.Delete(entity);
        }

        public void Remove(int Id)
        {
            T entity = FetchById(Id);

            Remove(entity);
        }

        public T FetchById(int Id)
        {
            return ActiveRecordMediator<T>.FindByPrimaryKey(Id);
        }

        public T[] FetchAll()
        {
            return ActiveRecordMediator<T>.FindAll();
        }
    }
}
